package com.health.controller;

import com.health.pojo.HealthAttributes;
import com.health.pojo.Users;
import com.health.service.HealthService;
import com.health.utils.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/healthSelect")
public class HealthServlet extends HttpServlet {
    HealthService healthService = new HealthService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String serviceType = "page";  // 默认分页查询
        String searchValue = "";       // 默认查询空
        int currentPage = 1;  // 当前页查询默认为第一页
        String searchExamineDate = ""; // 默认日期无
        request.setCharacterEncoding("utf-8");
        // 接收session的用户id参数
        Integer userId = ((Users) request.getSession().getAttribute("user")).getUserId();
        // 接收当前页码
        if (request.getParameter("currentPage") != null) {
            currentPage = Integer.parseInt(request.getParameter("currentPage"));
        }
        // 接收查询内容
        if (request.getParameter("searchText") != null) {
            searchValue = new String(request.getParameter("searchText").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 如果有查询内容设置业务类型为search
            serviceType = "search";
        }
        if (request.getParameter("searchExamineDate") != null) {
            searchExamineDate = request.getParameter("searchExamineDate");
        }
        // 执行业务层查询方法
        PageInfo<HealthAttributes> healthAttributesPageInfo = healthService.selectHealthData(userId, serviceType, currentPage, searchValue, searchExamineDate);
        // 判断是否查询到了数据
        if (healthAttributesPageInfo.getRecords() == null) {
            // 设置aside侧边栏状态
            request.setAttribute("asideStatus", 1);
            // 转发视图
            request.getRequestDispatcher("/restrictedPages/main.jsp").forward(request, response);
            return;
        }
        // 将分页后的数据放入请求域中
        request.setAttribute("healthAttributesPageInfo", healthAttributesPageInfo);
        System.out.println(healthAttributesPageInfo);
        // 设置aside侧边栏状态
        request.setAttribute("asideStatus", 1);
        // 转发视图
        request.getRequestDispatcher("/restrictedPages/main.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
